﻿namespace AutoRevit.Event;

/// <summary>
/// 外部时间处理的信息对象
/// </summary>
public class ExternalEventHandlerInfo
{
    /// <summary>
    /// 外部事件处理状态
    /// </summary>
    public enum ExternalEventHandlerStatus
    {
        /// <summary>
        /// 未运行
        /// </summary>
        NotRun,

        /// <summary>
        /// 运行中
        /// </summary>
        Runin,

        /// <summary>
        /// 已完成
        /// </summary>
        Finish,
    }

    private readonly Delegate _commandDelegate;

    private readonly List<object?> _params = new List<object?>();

    /// <summary>
    /// 
    /// </summary>
    /// <param name="commandDelegate"></param>
    /// <param name="params"></param>
    public ExternalEventHandlerInfo(Delegate commandDelegate, params object?[] @params)
    {
        _commandDelegate = commandDelegate;
        _params.AddRange(@params);
    }

    /// <summary>
    /// 外部事件处理状态
    /// 默认为 ExternalEventHandlerStatus.NotRun
    /// </summary>
    public ExternalEventHandlerStatus Status { get; private set; } = ExternalEventHandlerStatus.NotRun;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="app"></param>
    internal void Execute(UIApplication app)
    {
        try
        {
            Status = ExternalEventHandlerStatus.Runin;

            if (_commandDelegate.Method.GetParameters().Any())
            {
                _params.Insert(0, app);
                var param = _params?.Select(t => t is null ? t : Convert.ChangeType(t, t.GetType())).ToArray();
                _ = _commandDelegate.DynamicInvoke(param);
            }
            else
            {
                _ = _commandDelegate.DynamicInvoke();
            }
        }
        finally
        {
            Status = ExternalEventHandlerStatus.Finish;
        }
    }
}
